package com.jdk.learn.juc._06multithreadsecurity;

/**
 * Created by ricky
 * on 2018/1/31.
 *
 * 最基本的的生产者问题复现
 * 生产者消费者问题
 * 店员
 *
 */
public class TestProductAndConsumerFull {
    public static void main(String[] args) {
        Clerk2 Clerk2=new Clerk2();
        Product2 Product2=new Product2(Clerk2);
        Consumer2 Consumer2=new Consumer2(Clerk2);

        new Thread(Product2,"生产者1").start();
        new Thread(Consumer2,"消费者1").start();
        new Thread(Product2,"生产者2").start();
        new Thread(Consumer2,"消费者2").start();
    }
}

/**
 * 售货员
 */
class Clerk2{
    private int Product2nums=0;//产品数量

    /**
     * 拿货 取
     */
    public synchronized void get(){
        while (Product2nums >= 1) {//产品已满  用if的话可能会是负值  避免虚假唤醒的问题
            System.out.println("产品已满");
            try {
                this.wait();//等待  不生产了
            }catch (Exception e){}
        }
            System.out.println(Thread.currentThread().getName() +"-------    "+ ++Product2nums);
            this.notifyAll();//唤醒

    }
    /**
     * 卖货
     */
    public synchronized void sale(){
        while (Product2nums <= 0) {//产品缺货
            System.out.println("产品缺货");
            try {
                this.wait();//等待  没货了
            }catch (Exception e){}
        }
            System.out.println(Thread.currentThread().getName() +"-------    "+ --Product2nums);
            this.notifyAll();//唤醒

    }
}


/**
 * 生产者
 */
class Product2 implements Runnable{
    private Clerk2 Clerk2;

    public Product2(Clerk2 Clerk2) {
        this.Clerk2 = Clerk2;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Clerk2.get();
        }
    }
}


/**
 * 消费者
 */
class Consumer2 implements Runnable{
    private Clerk2 Clerk2;

    public Consumer2(Clerk2 Clerk2) {
        this.Clerk2 = Clerk2;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Clerk2.sale();
        }
    }
}
